<?php

namespace app\service;

use think\helper\Arr;

class TencentMapService
{
    /**
     * 线路坐标点集合转换
     * @see https://lbs.qq.com/service/webService/webServiceGuide/route/webServiceRoute#8
     * @param $coords
     * @return mixed
     */
    public static function decodeCoords($coords)
    {
        for ($i = 2; $i < count($coords) ; $i++) {
            $coords[$i] = $coords[$i - 2] + $coords[$i] / 1000000;
        }
        return $coords;
    }

    /**
     * 获取线路坐标点集合
     * @see https://lbs.qq.com/service/webService/webServiceGuide/route/webServiceRoute#3
     * @param array $from
     * @param array $to
     * @return array
     */
    public static function getWalkingCoords(array $from, array $to): array
    {
        $fromStr = join(',', [min($from), max($from)]);
        $toStr = join(',', [min($to), max($to)]);
        $url = 'https://apis.map.qq.com/ws/direction/v1/walking';
        $params = [
            'from' => $fromStr,
            'to' => $toStr,
            'key' => config('map.tencent.key'),
        ];
        [$isOk, $result] = curl($url, $params);
        if (!$isOk) {
            return [false, $result];
        }
        if (!$data = json_decode($result, true)) {
            return [false, 'api数据解析失败'];
        }
        if ($status = Arr::get($data, 'status')) {
            return [false, $status];
        }
        return [true, Arr::get($data, 'result.routes')];
    }
}